package com.group3.hospital.controller;

import com.group3.hospital.bean.User;
import com.group3.hospital.service.UserService;
import com.group3.hospital.shiro.ShiroUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import javax.annotation.Resource;

/**
 * @author 秀秀
 */
@Controller
@RequestMapping("/user")
@SessionAttributes(names = {"user"})
public class UserController {

    @Resource
    private UserService userService;

    //进入注册画面
    @RequestMapping("/registUi")
    public String registUi(){
        return "regist";
    }

    //执行注册操作
    @RequestMapping("/regist")
    public String regist(String username,String userTel,String userPassword1,String userPassword2){
        try {
            String salt = ShiroUtils.createSalt();
            // 根据盐对密码加密
            String password = ShiroUtils.createPassword(userPassword1, salt);
            userService.regist(username,password,Long.valueOf(userTel));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/user/loginUi";
    }

    //注册成功之后进入用户登录界面
    //执行登录操作
    //用户名及密码输入正确之后，进入主画面
    @RequestMapping("/loginUi")
    public String loginUi(String username,String userTel, String userPassword, Model model){
        try {
            User user = userService.login(username,Long.valueOf(userTel),userPassword);
            //判断用户名及密码是否和数据库中的一致
            if (user != null){
                model.addAttribute("user",user);
                return "redirect:/mainUi";
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "userLogin";
    }

    //退出登录
    @RequestMapping("/logout")
    public String logout(SessionStatus sessionStatus){
        sessionStatus.setComplete();
        return "redirect:/hello";
    }
}
